#!/bin/bash

# 克隆所有tree-sitter相关的仓库到self目录
# 使用--depth=1参数只克隆最新代码，节省空间和时间

echo "开始克隆tree-sitter仓库到self目录..."

# 检查是否在正确的目录中运行
if [ ! -f "clone-treesitter-repos.sh" ]; then
    echo "请在包含此脚本的目录中运行此脚本"
    exit 1
fi

# 定义检查目录完整性的函数
check_directory_integrity() {
    local dir_name="$1"
    
    # 检查目录是否存在
    if [ ! -d "$dir_name" ]; then
        return 1  # 目录不存在
    fi
    
    # 检查目录是否只有.git子目录
    local file_count=$(find "$dir_name" -mindepth 1 -maxdepth 1 ! -name ".git" | wc -l)
    
    if [ $file_count -eq 0 ]; then
        # 只有.git目录，说明克隆不完整
        echo "  检测到不完整的仓库目录: $dir_name (只有.git目录)"
        return 2  # 目录不完整
    fi
    
    # 检查是否有src/parser.c文件
    if [ ! -f "$dir_name/src/parser.c" ]; then
        echo "  检测到缺少关键文件的仓库目录: $dir_name (缺少src/parser.c)"
        return 3  # 缺少关键文件
    fi
    
    return 0  # 目录完整
}

# 定义清理不完整目录的函数
cleanup_incomplete_directory() {
    local dir_name="$1"
    
    echo "  清理不完整的目录: $dir_name"
    
    # 删除.git目录
    if [ -d "$dir_name/.git" ]; then
        rm -rf "$dir_name/.git"
    fi
    
    # 删除父目录
    rm -rf "$dir_name"
    
    echo "  已清理目录: $dir_name"
}

# 创建数组包含所有需要克隆的仓库
repos=(
    "https://github.com/tree-sitter/tree-sitter-bash.git"
    "https://github.com/tree-sitter/tree-sitter-c.git"
    "https://github.com/tree-sitter/tree-sitter-cpp.git"
    "https://github.com/tree-sitter/tree-sitter-css.git"
    "https://github.com/tree-sitter/tree-sitter-go.git"
    "https://github.com/tree-sitter/tree-sitter-html.git"
    "https://github.com/tree-sitter/tree-sitter-javascript.git"
    "https://github.com/tree-sitter/tree-sitter-lua.git"
    "https://github.com/amaanq/tree-sitter-luadoc.git"
    "https://github.com/tree-sitter/tree-sitter-markdown.git"
    "https://github.com/tree-sitter/tree-sitter-php.git"
    "https://github.com/tree-sitter/tree-sitter-ruby.git"
    "https://github.com/tree-sitter/tree-sitter-rust.git"
    "https://github.com/tree-sitter/tree-sitter-typescript.git"
)

# 遍历数组并克隆每个仓库
for repo in "${repos[@]}"; do
    # 从URL提取仓库名称
    repo_name=$(basename "$repo" .git)
    
    echo "处理仓库: $repo_name"
    
    # 检查目录完整性
    check_directory_integrity "$repo_name"
    check_result=$?
    
    case $check_result in
        0)
            echo "  目录 $repo_name 已存在且完整，跳过..."
            continue
            ;;
        1)
            # 目录不存在，继续克隆
            ;;
        2|3)
            # 目录存在但不完整，清理后重新克隆
            cleanup_incomplete_directory "$repo_name"
            ;;
    esac
    
    # 克隆仓库
    echo "  克隆 $repo_name..."
    if git clone --depth=1 "$repo" "$repo_name"; then
        echo "  成功克隆 $repo_name"
    else
        echo "  克隆 $repo_name 失败"
    fi
    
    echo ""
done

echo "克隆完成！"
